//
//  BillIndexViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-6-14.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BillIndexViewController.h"
#import "LoginController.h"
#import "GTMBase64.h"
#include "GDataXMLNode.h"
#import "ShoppingMallDetails.h"
#import "BillIndexCell.h"

@implementation BillIndexViewController
@synthesize segment, tableView, type;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [tableView release];
    [segment release];
    [type release];
    [myArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [app controllNum:1 setNavigationBar:NO animated:NO];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    app = [ELifeAppDelegate App];
    
    myArray = [[NSMutableArray arrayWithCapacity:100] retain];
    NSString* userid = [GetMyData getUserId];
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        lc.view.tag = 2001;
//        [self.view addSubview:lc.view];
        [self.navigationController pushViewController:lc animated:NO];
        [lc release];
        
        return;
    }
    
    [self setType:@"1"];

    [self openUrl];
    [app controllNum:1 setNavigationBar:NO animated:NO];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
       // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) openUrl
{
//    获得购物车订单列表
//    请求地址: /goods_order.php
//    请求参数: action  => get_goodsorder
//    user_id => 用户id
//    page => 当前页
//    limit => 每页显示记录数 
//    type => 记录类型  1:已成交订单  0:购物车记录 3:支付中. ============>需要加
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:10];
    [param setObject:@"get_goodsorder" forKey:@"action"];
    NSString* userid = [GetMyData getUserId];
    [param setObject:userid forKey:@"user_id"];
    [param setObject:@"1" forKey:@"page"];
    [param setObject:@"20" forKey:@"limit"];
    [param setObject:type forKey:@"type"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    NSString* urlRegister = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil], @"goods_order.php?"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];

}

-(void) iRequestFinished:(NSData*) data
{
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:data] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
    
    
    [myArray removeAllObjects];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:data] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    //    NSLog(@"--------root element:--------\n%@",rootElement);
    NSArray* children = [rootElement children];
    //NSLog(@"--------root's children:--------\n%@", children);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"--------body:--------\n%@", bodyElement);
    GDataXMLElement* goods = [[bodyElement elementsForName:@"order_lists"] objectAtIndex:0];
    GDataXMLElement* item = [goods elementsForName:@"order_list"];

    
    for (int i = 0; i<[item count]; i++) {
        
        NSString* name = [[[[item objectAtIndex:i] elementsForName:@"goods_name"] objectAtIndex:0] stringValue];
        NSLog(@"%@", name);
        NSString* id = [[[[item objectAtIndex:i] elementsForName:@"goods_id"] objectAtIndex:0] stringValue];
        NSString* order_id = [[[[item objectAtIndex:i] elementsForName:@"order_id"] objectAtIndex:0] stringValue];
        NSString* goods_price = [[[[item objectAtIndex:i] elementsForName:@"goods_price"] objectAtIndex:0] stringValue];
        if (name != nil && id != nil) {
            [myArray addObject:[NSArray arrayWithObjects:id, name, order_id, goods_price, nil]];
        }
        
    }
    
    NSLog(@"%@", myArray);
    [self.tableView reloadData];
}


-(IBAction) segmentAction
{
    if (segment.selectedSegmentIndex == 0) {
        [self setType:@"1"];
    }else if (segment.selectedSegmentIndex == 1) {
        [self setType:@"3"];
    }else if (segment.selectedSegmentIndex == 2) {
        [self setType:@"0"];
    }
    [self openUrl];
}


-(CGFloat) tableView:(UITableView*) tableView 
heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
	return 114;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [myArray count];
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"BillIndexCell";
    
    
    BillIndexCell* cell =  (BillIndexCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"BillIndexCell" owner:self options:nil];
        cell = [nib objectAtIndex:1];
    }

    NSString* name = [[myArray objectAtIndex:[indexPath row]] objectAtIndex:1];
    NSString* order_id = [[myArray objectAtIndex:[indexPath row]] objectAtIndex:2];
    NSString* goods_price = [[myArray objectAtIndex:[indexPath row]] objectAtIndex:3];

    [cell.titleName setText:[NSString stringWithFormat:@"商品名称：%@", name]];
    [cell.dingdan setText:[NSString stringWithFormat:@"订单号：%@", order_id]] ;
    [cell.jine setText:[NSString stringWithFormat:@"今额：%@", goods_price]];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* id = [[myArray objectAtIndex:[indexPath row]] objectAtIndex:0];
    
    ShoppingMallDetails* details = [[ShoppingMallDetails alloc] initWithStyle:UITableViewStyleGrouped];
    [details setGood_id:id];
    [self.navigationController pushViewController:details animated:YES];
    [details release];
}

-(void) registerOver:(NSString*) username
{
    UIView* view1 = [self.view viewWithTag:2001];
    [view1 removeFromSuperview];
}

@end
